import jwt from "jsonwebtoken";
import { secret } from "../api/auth/login.post";
export const isValidToken = async (
  authorization: string,
  event?: any
): Promise<boolean> => {
  const token = (await useStorage("redis").getItem(authorization)) as string;
  if (token) {
    return new Promise((resolve, reject) => {
      jwt.verify(token, secret, (err, decoded: any) => {
        if (err) {
          console.log(err);
          console.info("Error: " + err.message);
          return reject(false);
        }
        if (event) {
          const userId = decoded.data.uid;
          event.context.userId = userId;
        }
        return resolve(true);
      });
    });
  } else {
    return false;
  }
};
export default defineEventHandler(async (event) => {
  const pathname = getRequestURL(event).pathname;
  if (pathname.includes("/api")) {
    if (
      pathname !== "/api/auth/login" &&
      pathname !== "/api/auth/signUp" &&
      pathname !== "/api/auth/refreshToken"
    ) {
      const authorization = getHeaders(event).authorization?.replace(
        "Bearer ",
        ""
      ); // get authorization header
      if (authorization) {
        try {
          const a = await isValidToken(authorization, event);
          if (!a) {
            throw createError({ statusCode: 401, message: "token已失效" });
          }
        } catch (error) {
          throw createError({ statusCode: 401, message: "token已失效" });
        }
      }
    }
  }
});
